<?php
class UsersModel {
	public static function getByEmailPassword ($email, $password, $md5 = true) {
		$password = $md5 ? md5(conf('general.salt') . $password) : $password;

		return self::get(array(
			'limit' => 1, 
			'where' => 'email = ' . SleekPHP::db()->escSQL($email) . ' AND password = ' . SleekPHP::db()->escSQL($password)
		));
	}

	public static function getByID ($id) {
		return self::get(array(
			'limit' => 1, 
			'where' => 'users_id = ' . SleekPHP::db()->escSQL($id)
		));
	}

	public static function getByUsername ($username) {
		return self::get(array(
			'limit' => 1, 
			'where' => 'username = ' . SleekPHP::db()->escSQL($username)
		));
	}

	public static function getByEmail ($email) {
		return self::get(array(
			'limit' => 1, 
			'where' => 'email = ' . SleekPHP::db()->escSQL($email)
		));
	}

	public static function get ($config) {
		return SleekPHP::db()->get('users', $config);
	}

	public static function insert ($row) {
		return self::insertUpdate($row);
	}

	public static function update ($id, $row) {
		return self::insertUpdate($row, $id);
	}

	private static function insertUpdate ($row, $id = false) {
		$state		= isset($row['state']) ? $row['state'] : 0;
		$auth_level	= isset($row['auth_level']) ? $row['auth_level'] : 1;
		$email		= isset($row['email']) ? $row['email'] : '';
		$username	= isset($row['username']) ? $row['username'] : '';
		$password	= isset($row['password']) ? $row['password'] : '';

		$fields = array(
			'state'			=> $state, 
			'auth_level'	=> $auth_level, 
			'email'			=> $email, 
			'username'		=> $username, 
			'password'		=> $password
		);

		if ($id) {
			return SleekPHP::db()->update('users', $id, $fields);
		}
		else {
			return SleekPHP::db()->insert('users', $fields);
		}
	}

	public static function delete ($id) {
		return SleekPHP::db()->delete('users', $id);
	}

	public static function getRandomPassword ($length = 10) {
		$chars = '123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
		$len = strlen($chars);
		$pass = '';

		for ($i = 0; $i < $length; $i++) {
			$pass .= substr($chars, rand(0, $len - 1), 1);
		}

		return $pass;
	}
}
